package com.puman.ribbonconsumer.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheKey;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult;
import com.netflix.hystrix.contrib.javanica.command.AsyncResult;
import com.puman.ribbonconsumer.model.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.Future;

@Service
public class HelloService {
    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "helloFallback")
    public String helloService(){
        try {
            return restTemplate.getForEntity("http://HELLO-SERVICE/hello",String.class).getBody();
        }catch (Exception e){
            throw  new RuntimeException();
        }

    }
    public String helloFallback(Throwable e){
        System.out.println(e.getMessage());
        return "error";
    }
    public User helloFallback1(){
       // System.out.println(e.getMessage());
        return new User();
    }

    //同步执行调用
    @CacheResult(cacheKeyMethod = "getUserByIdCacheKey")
    @HystrixCommand
    public User getUserById(Long id){
        System.out.println("我进来了哈哈");
        return restTemplate.getForObject("http://HELLO-SERVICE/users?id={1}",User.class,id);
    }
    private String getUserByIdCacheKey(Long id){
        return id+"";
    }
    //异步执行调用
    @HystrixCommand
    public Future<User> getUserByIdAsync(final String id){
        System.out.println("我进来了哈哈");
        return  new AsyncResult<User>() {
            @Override
            public User invoke() {
                return restTemplate.getForObject("http://HELLO-SERVICE/users?id={1}",User.class,id);
            }
        };
    }

    @HystrixCollapser(batchMethod = "findAll",collapserProperties = {
            @HystrixProperty(name="timerDelayInMilliseconds",value = "100")
    })
    public User find(Long id){
        return null;
    }
    @HystrixCommand
    public List<User> findAll(List<Long> ids){
        return restTemplate.getForObject("http://USER-SERVICE/users?id={1}",
                List.class, StringUtils.join(ids,","));
    }

}
